<template>
  <div class="user-container">
    <h1 class="page-title">用户管理</h1>

    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input
        v-model="searchParams.search"
        placeholder="输入用户名或手机号搜索"
        class="search-input"
        clearable
        @clear="fetchUserList"
        @keyup.enter="fetchUserList"
      >
        <template #suffix>
          <el-icon class="cursor-pointer" @click="fetchUserList"
            ><Search
          /></el-icon>
        </template>
      </el-input>
      <el-button type="primary" @click="handleAddUser">
        <el-icon><Plus /></el-icon>
        新增用户
      </el-button>
    </div>

    <!-- 用户列表 -->
    <el-table
      :data="userList"
      style="width: 100%; margin-top: 20px"
      v-loading="loading"
      border
    >
      <el-table-column prop="name" label="姓名" width="80" />
      <el-table-column prop="username" label="用户名" min-width="120" />
      <el-table-column prop="phone" label="手机号码" min-width="150" />
      <el-table-column
        prop="department"
        label="所属单位"
        min-width="200"
        show-overflow-tooltip
      />
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column label="操作" width="220" fixed="right">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)"
            >编辑</el-button
          >
          <el-button
            size="small"
            type="warning"
            @click="handleResetPassword(scope.row)"
            >重置密码</el-button
          >
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.row)"
            v-if="scope.row.username !== 'admin'"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[10, 20, 30, 50, 100]"
        :total="total"
        v-model:page-size="searchParams.pageSize"
        v-model:current-page="searchParams.page"
        @current-change="handlePageChange"
        @size-change="handleSizeChange"
      />
    </div>

    <!-- 新增/编辑用户对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="userForm"
        :rules="formRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="userForm.name" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phone">
              <el-input v-model="userForm.phone" placeholder="请输入手机号码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="userForm.username"
            placeholder="请输入用户名"
            :disabled="isEdit"
          />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!isEdit">
          <el-input
            v-model="userForm.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="所属单位" prop="department">
          <el-input
            v-model="userForm.department"
            placeholder="请输入所属单位"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading"
          >确定</el-button
        >
      </template>
    </el-dialog>

    <!-- 重置密码对话框 -->
    <el-dialog v-model="passwordDialogVisible" title="重置密码" width="500px">
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="100px"
      >
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="passwordDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="handlePasswordSubmit"
          :loading="passwordSubmitLoading"
          >确定</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search } from '@element-plus/icons-vue'
import { userAPI } from '@/api/index.js'
// 数据状态
const loading = ref(false)
const submitLoading = ref(false)
const passwordSubmitLoading = ref(false)
const userList = ref([])
const total = ref(0)

// 搜索参数
const searchParams = reactive({
  page: 1,
  pageSize: 10,
  search: '',
})

// 对话框状态
const dialogVisible = ref(false)
const passwordDialogVisible = ref(false)
const dialogTitle = ref('新增用户')
const isEdit = ref(false)
const currentUser = ref(null)

// 表单引用
const formRef = ref()
const passwordFormRef = ref()

// 用户表单
const userForm = reactive({
  name: '',
  phone: '',
  username: '',
  password: '',
  department: '',
})

// 密码表单
const passwordForm = reactive({
  newPassword: '',
  confirmPassword: '',
})

// 密码验证函数
const validatePassword = (rule, value, callback) => {
  const pattern =
    /^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!%*#?&]{8,}$/
  if (!value) {
    callback(new Error('请输入密码'))
  } else if (!pattern.test(value)) {
    callback(new Error('密码必须包含字母、数字和特殊字符，且长度不少于8位'))
  } else {
    callback()
  }
}

const validateConfirmPassword = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请再次输入密码'))
  } else if (value !== passwordForm.newPassword) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

// 表单验证规则
const formRules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur',
    },
  ],
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    {
      min: 3,
      max: 20,
      message: '用户名长度在 3 到 20 个字符',
      trigger: 'blur',
    },
  ],
  password: [{ required: true, trigger: 'blur', validator: validatePassword }],
  department: [{ required: true, message: '请输入所属单位', trigger: 'blur' }],
}

// 密码验证规则
const passwordRules = {
  newPassword: [
    { required: true, trigger: 'blur', validator: validatePassword },
  ],
  confirmPassword: [
    { required: true, trigger: 'blur', validator: validateConfirmPassword },
  ],
}

// 获取用户列表
const fetchUserList = async () => {
  loading.value = true
  try {
    const response = await userAPI.getList(searchParams)
    if (response.code === 200) {
      userList.value = response.data.list
      total.value = response.data.total
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 页码改变
const handlePageChange = (page) => {
  searchParams.page = page
  fetchUserList()
}

const handleSizeChange = (size) => {
  searchParams.pageSize = size
  searchParams.page = 1 // 重置到第一页
  fetchUserList()
}

// 新增用户
const handleAddUser = () => {
  dialogTitle.value = '新增用户'
  isEdit.value = false
  dialogVisible.value = true
  resetForm()
}

// 编辑用户
const handleEdit = (row) => {
  dialogTitle.value = '编辑用户'
  isEdit.value = true
  currentUser.value = row
  Object.assign(userForm, {
    name: row.name,
    phone: row.phone,
    username: row.username,
    password: '',
    department: row.department,
  })
  dialogVisible.value = true
}

// 删除用户
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 "${row.name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    const response = await userAPI.delete(row.id)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      fetchUserList()
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 重置密码
const handleResetPassword = (row) => {
  currentUser.value = row
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
  passwordDialogVisible.value = true
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    submitLoading.value = true

    let response
    if (isEdit.value) {
      // 编辑时不发送密码字段
      const { password, ...updateData } = userForm
      response = await userAPI.update(currentUser.value.id, updateData)
    } else {
      response = await userAPI.create(userForm)
    }

    if (response.code === 200) {
      ElMessage.success(isEdit.value ? '编辑成功' : '新增成功')
      dialogVisible.value = false
      fetchUserList()
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  } finally {
    submitLoading.value = false
  }
}

// 提交密码重置
const handlePasswordSubmit = async () => {
  if (!passwordFormRef.value) return

  try {
    await passwordFormRef.value.validate()
    passwordSubmitLoading.value = true

    // 调用重置密码的API
    const response = await userAPI.resetPassword(currentUser.value.id, {
      newPassword: passwordForm.newPassword,
    })

    if (response.code === 200) {
      ElMessage.success('密码重置成功')
      passwordDialogVisible.value = false
      // 重置表单
      passwordForm.newPassword = ''
      passwordForm.confirmPassword = ''
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    console.error('密码重置失败:', error)
    ElMessage.error('密码重置失败')
  } finally {
    passwordSubmitLoading.value = false
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(userForm, {
    name: '',
    phone: '',
    username: '',
    password: '',
    department: '',
  })
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

onMounted(() => {
  fetchUserList()
})
</script>

<style scoped>
.user-container {
  padding: 20px;
}

.page-title {
  margin: 0 0 20px 0;
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.search-bar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.search-input {
  width: 300px;
}

.cursor-pointer {
  cursor: pointer;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>
